package com.mindskip.xzs.controller.admin;

import com.mindskip.xzs.base.MessageConstant;
import com.mindskip.xzs.base.Result;
import com.mindskip.xzs.domain.WJ;
import com.mindskip.xzs.service.WJService;
import com.mindskip.xzs.utility.QRCodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.File;
import java.util.UUID;

@RestController
@RequestMapping("/api/admin")
public class QRCodeController {
    private final WJService wjService;

    @Autowired
    public QRCodeController(WJService wjService) {
        this.wjService = wjService;
    }

    // 图片保存路径
    private static final String QR_CODE_DIR = "D:/qrcodes/";  // 修改为你自己硬盘路径
    private static final String BASE_URL = "http://localhost:8002/product";  // 跳转的目标页面地址

    @RequestMapping(value = "/generate", method = RequestMethod.POST)
    public Result generateQRCode(@RequestBody WJ wj) throws Exception {
        try{
            // 构建 URL
            String qrContent = BASE_URL + "?id=" + wj.getId();

            // 随机文件名
            String fileName = UUID.randomUUID().toString() + ".png";
            String filePath = QR_CODE_DIR + fileName;

            // 创建目录（如不存在）
            File dir = new File(QR_CODE_DIR);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 生成二维码图片
            QRCodeGenerator.generateQRCodeImage(qrContent, filePath, 300, 300);

            //添加二维码到数据库
            wj.setWjEwm("http://localhost:8000/qrcodes/" + fileName);
            wjService.updateByTwj(wj);
            return new Result(true, MessageConstant.ADD_WJ_FB_SUCCESS,wj.getWjEwm());
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_WJ_FAIL);
        }

    }
}
